import {toastTxt} from "./UniUtil";

export const baseURL = process.env.NODE_ENV === 'development'  ? 'api':  'http://api.blockhunter.group'

// https://blockhunter.group/
export const request = (url: string, method: 'POST' | 'GET', data?: any) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseURL + url, //接口地址：前缀+方法中传入的地址
            method: method,
            data: data || {}, //传递参数：传入的参数或者默认传递空集合
            header: {
                'Authorization': 'Bearer '+ uni.getStorageSync("token") || "" //自定义请求头信息
            },
            success: (res) => {
                console.log('ssssss', res)
                //返回的数据（不固定，看后端接口，这里是做了一个判断，如果不为true，用uni.showToast方法提示获取数据失败)
                if (res.data.code == 200 && !res.data?.data?.msg ) {
                    resolve(res.data.data)
                } else {
                    console.log('22222', res.data?.data?.msg)
                    if(res.data.code== 401 || (res.data.code ===0 && res.data.message === 'Unauthenticated.')){
                        uni.clearStorageSync()
                        uni.navigateTo({
                            url:'/pages/index/index'
                        })
                    }
                    toastTxt(res.data?.data?.msg || '网络异常')
                    reject(res.data.data)
                }
            },
            fail: (err) => {
                console.log(err)
                reject(err)
            }
        })
    })
}

export const ApiGET = (url:string, data?: any) => request(url, 'GET', data)
export const ApiPOST = (url:string, data?: any) => request(url, 'POST', data)
